package br.org.credfaz.ficha.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import br.org.credfaz.ficha.Db2ConnectionFactory;
import br.org.credfaz.ficha.modelo.Cliente;

public class ClienteDAO {

	private final Connection connection;

	public ClienteDAO() {
		try {
			connection = new Db2ConnectionFactory().getConnection();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}

	}

	public List<Cliente> lista() {
		try {
			List<Cliente> clientes = new ArrayList<Cliente>();
			PreparedStatement stmt = this.connection
					.prepareStatement("select idcliente,numcpfcnpj,nomereceita from cliente");

			ResultSet rs = stmt.executeQuery();

			while (rs.next()) {
				clientes.add(populaCliente(rs));
			}

			rs.close();
			stmt.close();

			return clientes;

		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
	
	public List<Cliente> pesquisa(String nome) {
		try {
			List<Cliente> clientes = new ArrayList<Cliente>();
			PreparedStatement stmt = this.connection
					.prepareStatement("select idcliente,numcpfcnpj,nomereceita from cliente WHERE nomereceita LIKE ? order by nomereceita");
			stmt.setString(1, nome+"%");
			
			System.out.println("dentro da dao pesquisa " + nome);

			ResultSet rs = stmt.executeQuery();

			while (rs.next()) {
				clientes.add(populaCliente(rs));
			}

			rs.close();
			stmt.close();

			return clientes;

		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public Cliente buscaPorId(Long id) {
		try {
			PreparedStatement stmt = this.connection
					.prepareStatement("select * from cliente where idcliente = ?");
			stmt.setLong(1, id);

			ResultSet rs = stmt.executeQuery();

			if (rs.next()) {
				return populaCliente(rs);
			}

			rs.close();
			stmt.close();

			return null;
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	private Cliente populaCliente(ResultSet rs) throws SQLException {
		Cliente cliente = new Cliente();

		cliente.setIdcliente(rs.getLong("idcliente"));
		cliente.setNomereceita(rs.getString("nomereceita"));
		cliente.setNumcpfcnpj(rs.getString("numcpfcnpj"));
		
		if(rs.getString("numcpfcnpj").length()> 11){
			String cnpj = rs.getString("numcpfcnpj");
			String cnpjformatado = cnpj.substring(0,2)+"."+cnpj.substring(2,5)+"."+cnpj.substring(5,8)+"/"+cnpj.substring(8,12)+"-"+cnpj.substring(12,14);
		cliente.setCpfformatado(cnpjformatado);
		}else{
			String cpf = rs.getString("numcpfcnpj");
			String cpfformatado = cpf.substring(0,3)+"."+cpf.substring(3,6)+"."+cpf.substring(6,9)+"-"+cpf.substring(9,11);
		cliente.setCpfformatado(cpfformatado);
		}

		return cliente;
	}

}
